<?php
namespace app\store\controller\shop;

use app\store\controller\Controller;
/**
 * 店员管理
 * Class Index
 * @package app\store\controller
 */
class Clerk extends Controller
{
    public function index()
    {
        $list = db("shop_clerk")->alias('sc')->join("shop s" , 's.shop_id = sc.shop_id')->join("user u",'u.user_id = sc.user_id')->field("u.nickname,u.mobile,s.shop_name,sc.*")->order(['sc.clerk_id' => 'DESC'])->paginate(15, false, ['query' => $this->request->request()]);
        return $this->fetch('index', compact('list'));
    }
    
    public function add() {
        return $this->post();
    }
    
    public function edit() {
        $id = $this->request->param('clerk_id/d' , 0);
        if( !$data = db("shop_clerk")->where(['clerk_id' => $id])->find()){
            $this->error("数据不存在");
        }
        if( $data['user_id'] > 0 ) {
            $data['user_info'] = db('user')->where(['user_id' => $data['user_id']])->field("nickname,user_id,avatar")->find();
        }
        return $this->post( $data );
    }
    
    public function delete() {
        $id = $this->request->post('clerk_id' , 0);
        if( $id <= 0 ) $this->error('参数错误，请核对');
        $res = db('shop_clerk')->where(['clerk_id' => $id])->delete();
        if( $res ) {
            $this->success('删除成功');
        } else {
            $this->error("操作失败");
        }
    }
    
    public function post( $save_data = [] ) {
        if( $this->request->isAjax()) {
            $params = $this->postData('clerk');
            $params['create_time'] = time();
            $clerk_id = $this->request->param('clerk_id/d',0);
            if( $clerk_id > 0 ) {
                $res = db('shop_clerk')->where(['clerk_id' => $clerk_id])->update($params);
                if( $res ) {
                    $this->success('店员信息修改成功');
                } else {
                    $this->error("编辑失败");
                }
            } else {
                $res = db('shop_clerk')->insert($params);
                if( $res ) {
                    $this->success('新增店员成功');
                } else {
                    $this->error("新增失败");
                }
            }
        }
        $shop = db("shop")->where(['status' => 1])->field("shop_id,shop_name")->select();
        return $this->fetch('' , compact('shop','save_data'));
    }
}
